package com.bawei.module_sign

import android.os.Build
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.BaseActivity
import com.bawei.lib_common.base.state.Empty
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.Success
import com.bawei.module_sign.adapter.SignAdapter
import com.bawei.module_sign.databinding.ActivityClockBinding
import com.bawei.module_sign.model.ClockModel
import com.bawei.module_sign.model.SignModelItem
import com.bawei.module_sign.ui.SignViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.Calendar


@AndroidEntryPoint
@Route(path = Router.Ui.ClockActivity)
class ClockActivity : BaseActivity<SignViewModel, ActivityClockBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_clock
    override val mViewModel: SignViewModel by viewModels()
    private var hasMorningCheckIn = false // 标记是否已上午打卡
    private var todayCheckInCompleted = false // 标记当日是否已完成二次打卡

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        // 初始化时间显示
        updateTimeDisplay()

        // 启动定时器每秒更新时间
        val handler = Handler(Looper.getMainLooper())
        val runnable = object : Runnable {
            @RequiresApi(Build.VERSION_CODES.O)
            override fun run() {
                updateTimeDisplay()
                handler.postDelayed(this, 1000)
            }
        }
        handler.post(runnable)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initListener() {
        mBinding.btnClockIn.setOnClickListener {
            val currentLocation = mBinding.etUsername.text.toString()
            if (currentLocation.isBlank()) {
                Toast.makeText(this, "请输入当前位置", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 判断当前是上午还是下午班次
            val currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
            val clockType = if (currentHour < 12) "morningCheckIn" else "afternoonCheckIn"

            if (clockType == "morningCheckIn" && !hasMorningCheckIn) {
                // 上午首次打卡逻辑
                handleMorningCheckIn(currentLocation)
            }else if (clockType == "afternoonCheckIn" && hasMorningCheckIn && !todayCheckInCompleted) {
                // 下午二次打卡逻辑（需已上午打卡且未完成当日打卡）
                handleAfternoonCheckIn(currentLocation)
            } else {
                // 当日已完成打卡，提示禁用
                showToast("今日已完成打卡，无需重复操作")
            }
        }
    }
    // 上午打卡逻辑：记录时间、标记状态
    @RequiresApi(Build.VERSION_CODES.O)
    private fun handleMorningCheckIn(location: String) {
        val clockModel = ClockModel(
            morningCheckIn = LocalDateTime.now().toString(),
            afternoonCheckIn = "",
            currentLocation = location,
            location = location,
            status = "NORMAL",
            workDate = LocalDate.now().toString(),
            userId = 1833,
            user = 1833,
            id = 1
        )
        mViewModel.getClock(clockModel)
        hasMorningCheckIn = true // 标记已上午打卡
        updateButtonState() // 更新按钮状态（可选：上午打卡后可置灰，或仅二次打卡后禁用）
    }

    override fun initData() {
        lifecycleScope.launch {
            mViewModel.mClockState.collectLatest { event ->
                when (event) {
                    is Failed -> {}
                    Loading -> {}
                    Success -> {
                        updateClockStatus()
                        showToast("打卡成功")
                    }

                    Empty -> {
                        showToast("打卡失败")
                    }
                }
            }

        }
    }
    // 下午打卡逻辑：补全数据、标记完成、上传列表
    @RequiresApi(Build.VERSION_CODES.O)
    private fun handleAfternoonCheckIn(location: String) {
        val clockModel = ClockModel(
            morningCheckIn = mViewModel.mClockListData?.firstOrNull()?.morningCheckIn ?: "",
            afternoonCheckIn = LocalDateTime.now().toString(),
            currentLocation = location,
            location = location,
            // 关键：调用状态判断方法，标记正常/迟到/早退
            status = checkAttendanceStatus(),
            workDate = LocalDate.now().toString(),
            userId = 1833,
            user = 1833,
            id = 1
        )
        mViewModel.getClock(clockModel)
//        todayCheckInCompleted = true // 标记当日已完成打卡
        updateButtonState() // 禁用按钮
//        uploadToAttendanceList(clockModel) // 上传到图4的列表
    }
    /**
     * 判断考勤状态：
     * - 上午打卡晚于 09:00 → 迟到
     * - 下午打卡早于 18:00 → 早退
     * - 未打卡 → 缺勤
     * - 其他 → 正常
     */
    @RequiresApi(Build.VERSION_CODES.O)
    private fun checkAttendanceStatus(): String {
        val currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
        val currentMinute = Calendar.getInstance().get(Calendar.MINUTE)
        val today = LocalDate.now().toString()

        // 模拟班次时间（可根据实际需求动态配置）
        val morningStart = LocalTime.of(9, 0)
        val afternoonEnd = LocalTime.of(18, 0)

        // 上午打卡状态
        val morningCheckInTime = LocalDateTime.parse(
            mViewModel.mClockListData?.firstOrNull()?.morningCheckIn,
            DateTimeFormatter.ISO_LOCAL_DATE_TIME
        ).toLocalTime()
        val isMorningLate = morningCheckInTime.isAfter(morningStart)

        // 下午打卡状态
        val afternoonCheckInTime = LocalTime.of(currentHour, currentMinute)
        val isAfternoonEarly = afternoonCheckInTime.isBefore(afternoonEnd)

        return when {
            todayCheckInCompleted.not() -> "缺勤"
            isMorningLate -> "迟到"
            isAfternoonEarly -> "早退"
            else -> "正常"
        }
    }
    /**
     * 更新打卡按钮状态：当日完成打卡后禁用
     */
    private fun updateButtonState() {
        mBinding.btnClockIn.isEnabled = !todayCheckInCompleted
        mBinding.btnClockIn.alpha = if (todayCheckInCompleted) 0.5f else 1f // 置灰
    }
    @RequiresApi(Build.VERSION_CODES.O)
    private fun updateTimeDisplay() {
        val currentTime = LocalDateTime.now()
        mBinding.tvTime.text = currentTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"))
        mBinding.tvDate.text = currentTime.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE"))

        // 更新打卡时间段显示
        val currentHour = currentTime.hour
        if (currentHour < 12) {
            mBinding.tvShift.text = "上午打卡"
            mBinding.tvShiftTime.text = "09:00-12:00"
        } else {
            mBinding.tvShift.text = "下午打卡"
            mBinding.tvShiftTime.text = "13:30-18:00"
        }
    }

    private fun updateClockStatus() {
        // 根据最新打卡记录更新界面状态
        val records = mViewModel.mClockListData
        if (records.isNotEmpty()) {
            val lastRecord = records.last()
            if (lastRecord.morningCheckIn.isNotEmpty() && lastRecord.afternoonCheckIn.isEmpty()) {
                mBinding.btnClockIn.text = "下班打卡"
                mBinding.tvShift.text = "已上班打卡，请在下班时再次打卡"
            } else {
                mBinding.btnClockIn.text = "上班打卡"
                mBinding.tvShift.text = "今日打卡已完成"
            }
        }
    }
}